# AI_AUTO_PLAY_MOD
#
# by jdog5000
# version 1.25

from CvPythonExtensions import *
import CvTopCivs
import CvUtil
import PyHelpers		
import Popup as PyPopup
#import CvEventManager

# globals
gc = CyGlobalContext()
PyPlayer = PyHelpers.PyPlayer
PyInfo = PyHelpers.PyInfo
game = CyGame()

class AIAutoPlay :

    def __init__(self, customEM, config = None ) :

        CvUtil.pyPrint("Initializing AIAutoPlay Mod")

        self.LOG_DEBUG = False
        self.SHOW_NEW_LEADER_POPUP = True
        self.blockPopups = True
        if( not config == None ) :
            self.LOG_DEBUG = config.getboolean("AIAutoPlay", "DebugMode", False)
            self.SHOW_NEW_LEADER_POPUP = config.getboolean("AIAutoPlay", "ShowNewLeaderPopup", True)
            self.blockPopups = config.getboolean("AIAutoPlay", "BlockPopups", True)

        self.EventKeyDown=6
        self.TurnsToAuto = 10
        self.toAIChooserPopup = 7000
        self.abdicatePopup = 7001

        self.playerID = 0

        self.AutoCounter = 0

        self.bAutoMoves = False

        # These settings don't work currently
        self.bPause = False
        self.bPauseEveryTen = False
        self.bWakeOnWar = False
        self.bWakeOnVic = True

        self.AutoTypes={
            0 : 'No automation',
            1 : 'Fully Automate',
            #2 : 'Automate unit moves only (not fully tested)',
            #3 : 'Debug Mode (will reveal entire world!!!)',
            }

        self.customEM = customEM

        self.customEM.addEventHandler( "kbdEvent", self.onKbdEvent )

        self.customEM.setPopupHandler( self.toAIChooserPopup, ["toAIChooserPopup",self.AIChooserHandler,self.blankHandler] )
        self.customEM.setPopupHandler( self.abdicatePopup, ["abdicatePopup",self.abdicateHandler,self.blankHandler] )

        #print "from EM: ", CvEventManager.CvEventManager.EventKeyUp
        

        if( self.blockPopups ) :
            print "Removing some event handlers"
            try :
                self.customEM.removeEventHandler( "cityBuilt", customEM.onCityBuilt )
                self.customEM.addEventHandler( "cityBuilt", self.onCityBuilt )
            except ValueError :
                print "Failed to remove 'onCityBuilt', perhaps not registered"
                self.customEM.setEventHandler( "cityBuilt", self.onCityBuilt )
            
            try :
                self.customEM.removeEventHandler( "BeginGameTurn", customEM.onBeginGameTurn )
                self.customEM.addEventHandler( "BeginGameTurn", self.onBeginGameTurn )
            except ValueError :
                print "Failed to remove 'onBeginGameTurn', perhaps not registered"
                self.customEM.setEventHandler( "BeginGameTurn", self.onBeginGameTurn )
            

    def blankHandler( self, playerID, netUserData, popupReturn ) :
        # Dummy handler to take the second event for popup
        return

    def onKbdEvent( self, argsList ) :
        'keypress handler'
        eventType,key,mx,my,px,py = argsList

        if ( eventType == self.EventKeyDown ):
	    theKey=int(key)

	    if( theKey == int(InputTypes.KB_X) and self.customEM.bShift and self.customEM.bCtrl ) :
                # Get it?  Shift ... control ... to the AI
                if( game.getAIAutoPlay() > 0 ) :
                    self.TurnsToAuto = 0
                    self.setAIAutoPlay( )
                else :
                    self.toAIChooser()

            if( theKey == int(InputTypes.KB_M) and self.customEM.bShift and self.customEM.bCtrl ) :
                # Toggle auto moves
                if( self.LOG_DEBUG ) : CyInterface().addImmediateMessage("Moving your units...","")
                #self.playerID = gc.getActivePlayer().getID()
                self.TurnsToAuto = 1
                self.setAIAutoPlay( )

    def onBeginGameTurn( self, argsList):
        'Called at the beginning of the end of each turn'
        iGameTurn = argsList[0]
        if( game.getAIAutoPlay() == 0 ) :
            CvTopCivs.CvTopCivs().turnChecker(iGameTurn)

    def onCityBuilt(self, argsList):
        'City Built'
        city = argsList[0]
        if (city.getOwner() == CyGame().getActivePlayer() and game.getAIAutoPlay() == 0 ):
                #self.customEM.__eventEditCityNameBegin(city, False)
                self.customEM.onCityBuilt(argsList)
        else : 
                CvUtil.pyPrint('City Built Event: %s' %(city.getName()))

    def toAIChooser( self ) :
        'Chooser window for when user switches to AI auto play'

        popup = PyPopup.PyPopup(self.toAIChooserPopup,contextType = EventContextTypes.EVENTCONTEXT_ALL)
        popup.setHeaderString( 'Turn on AI Auto Control?' )
        popup.setBodyString( 'How many turns would you like the AI to control?' )
        popup.addSeparator()
        popup.createPythonEditBox( '10', 'Number of turns to turn over to AI', 0)
        
        popup.createPythonPullDown( 'Choose type of automation', 2 )
        for i in range(0,len(self.AutoTypes)) :
            popup.addPullDownString( self.AutoTypes[i], i, 2 )

        popup.popup.setSelectedPulldownID( 1, 2 )
            
        #popup.createPythonCheckBoxes( 4, 3 )
        #popup.setPythonCheckBoxText( 0, 'Pause at turn end', 'Pauses automation at the end of the turn, so you can inspect things', 3 )
        #popup.setPythonCheckBoxText( 1, 'Pause every 10', 'Pauses automation every 10 turns', 3 )
        #popup.setPythonCheckBoxText( 2, 'Cancel on war declared', 'Cancel automation if your civ becomes involved in a war', 3 )
        #popup.setPythonCheckBoxText( 3, 'Wake-up on game end', 'If someone (your civ?) wins, automation cancelled', 3 )

        popup.addSeparator()

        popup.addButton('Cancel')

        popup.launch()

    def AIChooserHandler( self, playerID, netUserData, popupReturn ) :
        'Handles AIChooser popup'
        if( popupReturn.getButtonClicked() == 0 ):  # if you pressed cancel
            return
        
        numTurns = 0
        self.playerID = playerID
        if( popupReturn.getEditBoxString(0) != '' ) :
            numTurns = int( popupReturn.getEditBoxString(0) )

        autoIdx = popupReturn.getSelectedPullDownValue( 2 )
        
        if( autoIdx == 0 ) :
            if( self.LOG_DEBUG ) : CyInterface().addImmediateMessage("Clearing all automation","")
            self.clearAllAutomation( )
        elif( autoIdx == 1 and numTurns > 0 ) :
            if( self.LOG_DEBUG ) : CyInterface().addImmediateMessage("Fully automate","")
            self.abdicate( numTurns = numTurns, voluntary = 1 )
        elif( autoIdx == 2 and numTurns > 0 ) :
            if( self.LOG_DEBUG ) : CyInterface().addImmediateMessage("Auto Move","")
            self.setAutoMoves( numTurns )
        elif( autoIdx == 3 and numTurns > 0 ) :
            if( self.LOG_DEBUG ) : CyInterface().addImmediateMessage("Debug Mode","")
            self.setDebugMode( numTurns )

        # How to read out checkboxes?  popupReturn doesn't seem to have a function
        #bitField = popupReturn.getCheckBoxBitfield( 3 )
        #self.bPause =
        #CyInterface().addImmediateMessage("bitfieldsize: %d"%(len(bitField)),"")

    def abdicate( self, numTurns = -1, voluntary = 0 ) :
        'Turn over control to the AI'
        if( numTurns > 0 ) :
            self.TurnsToAuto = numTurns

        if( self.TurnsToAuto < 1 ) :
            return

        if( voluntary and self.SHOW_NEW_LEADER_POPUP ) :
            popup = PyPopup.PyPopup(self.abdicatePopup,contextType = EventContextTypes.EVENTCONTEXT_ALL)
            popup.setHeaderString( 'There is a new leader!!!' )
            if( voluntary ) :
                bodStr = 'Old age has finally caught up with you and you decide to abdicated rule.\n\n'
            else :
                bodStr = 'Terrible news:  Coniving rivals have overthrown you in a coup!  '
                bodStr = 'A little to much "Let them eat cake" perhaps?\n\n'
            bodStr = bodStr + 'However, there is good news!  '
            bodStr = bodStr + 'Mystical advisors report that you will be reincarnated and return to power in %d turns.\n\n'%(self.TurnsToAuto)
            bodStr = bodStr + 'In the meantime, you can only hope your successor proves worthy.'
            popup.setBodyString( bodStr )
            popup.launch()
        else :
            self.setAIAutoPlay()
        
    def abdicateHandler( self, playerID, netUserData, popupReturn ) :
        'Handle abdicate popup'
        self.setAIAutoPlay()

    def setAIAutoPlay( self ) :
        game.setAIAutoPlay( self.TurnsToAuto )

   

## --------------- All functions below this line are not currently used, may not perform as expected -------------------

    def setAutoMoves( self, numTurns ) :
        if( numTurns > 0 ) :
            gc.getPlayer(self.playerID).setAutoMoves( 1 )

    def clearAllAutomation( self ) :
        game.setAIAutoPlay( 0 )
        gc.getPlayer(self.playerID).setAutoMoves( False )
        if( game.isDebugMode( ) ) :
            game.toggleDebugMode( )

    def setDebugMode ( self, numTurns ) :
        if( not game.isDebugMode( ) ) :
            game.toggleDebugMode( )
        self.abdicate( numTurns, 1 )

    def onChangeWar( self, argsList ) :
        bIsWar = argsList[0]
	iPlayer = argsList[1]
	iRivalTeam = argsList[2]
        if( game.getAIAutoPlay( ) > 0 ) :
            if( self.bWakeOnWar and bIsWar ) :
                if( iPlayer == self.playerID or iRivalTeam == gc.getPlayer(playerID).getTeam() ) :
                    CyInterface().addImmediateMessage("Wake on war","")

    def onVictory( self, argsList ) :
        iTeam, iVictory = argsList
        if( game.getAIAutoPlay( ) > 0 ) :
            if( self.bWakeOnVic ) :
                CyInterface().addImmediateMessage("Wake on victory","")
